<?php
use Illuminate\Database\Eloquent\Model;

class agentrewardModel extends Model
{
	protected $table 		= 'agent_reward';
	public	  $primaryKey	= 'id';

	// 追加属性
    protected $appends = ['status_name', 'class_text', 'level_info'];

    // 分销佣金状态  table: commission_reward, field: status
    const COMMISSION_REWARD_STATUS_WAITING = 0;  // 未结算、待入账
    const COMMISSION_REWARD_STATUS_ACCOUNTED = 1;  // 已结算、已入账
    const COMMISSION_REWARD_STATUS_BACK = -1;  // 已退回
    const COMMISSION_REWARD_STATUS_CANCEL = -2;  // 已取消

    protected function serializeDate($date)
    {
        return $date->format('Y-m-d H:i:s');
    }


    public function getLevelInfoAttribute()
    {
        return !empty($this->attributes['agent_level']) ? agentlevelModel::where('level', $this->attributes['agent_level'])->first() : [];
    }

    /**
     * 获取佣金明细
     *
     * @return array
     */
    public static function getList($params)
    {
        $page = $params['page'] ?? 1;
        $per_page = $params['per_page'] ?? 10;

        // 获取佣金记录
        $total = self::buildSearch($params)->count();
        $data = self::buildSearch($params)
            ->with(['buyer', 'order'])
            ->orderBy('id', 'desc')
            ->offset(($page - 1) * $per_page)
            ->limit($per_page)
            ->get();

        $rewards = [
            'current_page' => $page,
            'last_page' => ceil($total / $per_page),
            'per_page' => $per_page,
            'total' => $total,
            'data' => $data,
        ];

        // 获取查询条件的总佣金
        $type = $params['type'] ?? 'all';
        if ($type == 'all') {
            // 收入，包含待入账
            $total_money = self::buildSearch($params)->income()->sum('commission');
        } else {
            $total_money = self::buildSearch($params)->sum('commission');
        }

        return ['rewards' => $rewards, 'total_money' => $total_money,];
    }


    /**
     * 构建查询条件
     */
    public static function buildSearch($params)
    {
        $user = \app\service\auth::getUser();

        $start = date('Y-m-d');
        $end = date('Y-m-d', strtotime('+1 day'));
        $date = explode('-', $params['date'] ?? '');
        if (!empty($date) && count($date) == 2) {
            $start = $date[0];
            $end = $date[1] . ' 23:59:59';
        }

        $rewards = self::where('agent_id', $user->id);

        $type = $params['type'] ?? 'all';
        if ($type != 'all' && in_array($type, ['waiting', 'back', 'accounted', 'cancel'])) {
            $rewards = $rewards->{$type}();
        }

        $rewards = $rewards->whereBetween('created_at', [$start, $end]);

        return $rewards;
    }

    public function getStatusNameAttribute($value)
    {
        $status_name = '';

        switch ($this->attributes['status']) {
            case self::COMMISSION_REWARD_STATUS_BACK:
                $status_name = '已退回';
                break;
            case self::COMMISSION_REWARD_STATUS_WAITING:
                $status_name = '待入账';
                break;
            case self::COMMISSION_REWARD_STATUS_ACCOUNTED:
                $status_name = '已入账';
                break;
            case self::COMMISSION_REWARD_STATUS_CANCEL:
                $status_name = '已取消';
                break;
        }

        return $status_name;
    }

    public function getClassTextAttribute($value)
    {
        $class_text = "";

        switch ($this->attributes['class']) {
            case 'pingjifenhong':
                $config_text = configModel::query()->where('type',19)->where('key', 'pingjifenhong_text')->value('value');
                $class_text = $config_text?:'平级奖励';
                break;
            case 'jichafenhong':
                $config_text = configModel::query()->where('type',19)->where('key', 'jichafenhong_text')->value('value');
                $class_text = $config_text?:'级差奖励';
                break;
        }

        return $class_text;
    }

    /**
     * 待入账
     */
    public function scopeWaiting($query)
    {
        return $query->where('status', self::COMMISSION_REWARD_STATUS_WAITING);
    }

    /**
     * 已退回
     */
    public function scopeBack($query)
    {
        return $query->where('status', self::COMMISSION_REWARD_STATUS_BACK);
    }

    /**
     * 已入账
     */
    public function scopeAccounted($query)
    {
        return $query->where('status', self::COMMISSION_REWARD_STATUS_ACCOUNTED);
    }

    /**
     * 已取消
     */
    public function scopeCancel($query)
    {
        return $query->where('status', self::COMMISSION_REWARD_STATUS_CANCEL);
    }

    /**
     * 待入账和已入账
     *
     * @return void
     */
    public function scopeIncome($query)
    {
        return $query->where('status', 'in', [self::COMMISSION_REWARD_STATUS_ACCOUNTED, self::COMMISSION_REWARD_STATUS_WAITING]);
    }

    public function order()
    {
        return $this->belongsTo(orderModel::class, 'order_id', 'id')->select([
            'id', 'type', 'order_sn', 'member_id', 'activity_type', 'goods_amount', 'dispatch_amount',
            'status', 'total_amount', 'score_amount', 'total_fee', 'discount_fee', 'pay_fee', 'score_fee',
            'goods_original_amount', 'pay_type', 'paytime', 'ext', 'created_at',
        ]);
    }

    public function orderItem()
    {
        return $this->belongsTo(orderitemModel::class, 'order_item_id', 'id')->select( 'id','goods_title','goods_id','goods_sku_text','goods_num','pay_price');
    }

    public function buyer()
    {
        return $this->belongsTo(memberModel::class, 'buyer_id', 'id')->select('id','nickname','realname','phone');
    }

    public function agent()
    {
        return $this->belongsTo(memberModel::class, 'agent_id', 'id')->select('id','nickname','realname','phone');
    }

}

